#!/bin/sh
#

# PROVIDE: ldpbiconfig
# REQUIRE: mountcritremote cleanvar
# BEFORE:  DAEMON

. /etc/rc.subr

name="ldpbiconfig"
ldconfig_command="/sbin/ldconfig"
ldpbiconfig_dirlist=${ldpbiconfig_dirlist:-"/usr/local/etc/ldpbiconfig"}
start_cmd="ldpbiconfig_start"
stop_cmd=":"

ldpbiconfig_start()
{
	while read dir
	do
		hintmod="`echo $dir | sed 's|/|%|g'`"
		ldpbiconfig_init "$dir" "%${hintmod}"

	done < $ldpbiconfig_dirlist
}

# Enable a PBI's ldconfig hints file
ldpbiconfig_init()
{
	ldconfig_local_dirs="${1}/libdata/ldconfig"
	ldconfig_local32_dirs="${1}/libdata/ldconfig"
	ldconfig_paths="${1}/lib ${1}/lib/compat/pkg"
	ldconfig32_paths="${1}/lib ${1}/lib/compat/pkg"
	echo "ldpbiconfig for: ${1}"
	ldconfig=${ldconfig_command}
	local _files _ins

	_ins=
	checkyesno ldconfig_insecure && _ins="-i"
	if [ -x "${ldconfig_command}" ]; then
		_LDC="/lib /usr/lib"
		for i in ${ldconfig_local_dirs}; do
			if [ -d "${i}" ]; then
				_files=`find ${i} -type f`
				if [ -n "${_files}" ]; then
					ldconfig_paths="${ldconfig_paths} `cat ${_files} | sort -u`"
				fi
			fi
		done
		for i in ${ldconfig_paths} /etc/ld-elf.so.conf; do
			if [ -r "${i}" ]; then
				_LDC="${_LDC} ${i}"
			fi
		done
		if [ -d "/usr/local/lib" ] ; then _LDC="${_LDC} /usr/local/lib" ; fi
		if [ -d "/usr/local/lib/compat/pkg" ] ; then _LDC="${_LDC} /usr/local/lib/compat/pkg" ; fi
		check_startmsgs && echo 'ELF ldconfig path:' ${_LDC}
		${ldconfig} -elf -f "/var/run/ld-elf.so.hints${2}" ${_ins} ${_LDC}

		case `sysctl -n hw.machine_arch` in
		amd64)
			for i in ${ldconfig_local32_dirs}; do
				if [ -d "${i}" ]; then
					_files=`find ${i} -type f`
					if [ -n "${_files}" ]; then
						ldconfig32_paths="${ldconfig32_paths} `cat ${_files} | sort -u`"
					fi
				fi
			done
			_LDC=""
			for i in ${ldconfig32_paths}; do
				if [ -r "${i}" ]; then
					_LDC="${_LDC} ${i}"
				fi
			done
			if [ -d "/usr/local32/lib" ] ; then _LDC="${_LDC} /usr/local32/lib" ; fi
			if [ -d "/usr/local32/lib/compat/pkg" ] ; then _LDC="${_LDC} /usr/local32/lib/compat/pkg" ; fi
			check_startmsgs &&
			    echo '32-bit compatibility ldconfig path:' ${_LDC}
			${ldconfig} -32 -m -f "/var/run/ld-elf32.so.hints${2}" ${_ins} ${_LDC}
			;;
		esac

		# Legacy aout support for i386 only
		case `sysctl -n hw.machine_arch` in
		i386)
			# Default the a.out ldconfig path.
			: ${ldconfig_paths_aout=${ldconfig_paths}}
			_LDC=/usr/lib/aout
			for i in ${ldconfig_paths_aout} /etc/ld.so.conf; do
				if [ -r "${i}" ]; then
					_LDC="${_LDC} ${i}"
				fi
			done
			check_startmsgs && echo 'a.out ldconfig path:' ${_LDC}
			${ldconfig} -aout -f "/var/run/ld.so.hints${2}" ${_ins} ${_LDC}
			;;
		esac
	fi
}

load_rc_config $name
run_rc_command "$1"
